package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    FileStorageService fileStorageService;
    @Value("${file.oss.prefix}")
    private String prefix;
    @Value("${file.oss.web-site}")
    private String webSite;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * TODO 自媒体图片上传功能
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
        //参数检查
        if (multipartFile == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的文件");
        }
        //当前线程中获取用户ID
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        //文件大小大于2MB
        if (!checkFileSize(multipartFile)) {
            CustException.cust(AppHttpCodeEnum.PARAM_IMAGE_SIZE_ERROR, "请上传小于2MB的文件");
        }
        if (!checkFileSuffix(multipartFile.getOriginalFilename())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }
        //上传图片到oos
        String fileId = null;
        try {
            String fileName = UUID.randomUUID().toString().replace("-", "");
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
            fileId = fileStorageService.store(prefix, fileName + suffix, multipartFile.getInputStream());
            log.info("阿里云OSS 文件 fileId: {}", fileId);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("阿里云文件上传失败 uploadPicture error: {}", e);
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "服务器繁忙请稍后重试");
        }
        //保存素材到数据库
        WmMaterial wmMaterial = WmMaterial.builder().userId(user.getId())
                .type((short) 0).isCollection((short) 0)
                .createdTime(new Date()).url(fileId).build();
        save(wmMaterial);
        //拼接图片路径返回
        wmMaterial.setUrl(webSite + fileId);
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * TODO 自媒体图片列表查询
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //参数检查
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //分页查询
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //获取当前登录的用户
        Integer UserId = WmThreadLocalUtils.getUser().getId();
        wrapper.eq(WmMaterial::getUserId, UserId);
        //是否收藏
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1) {
            wrapper.eq(WmMaterial::getIsCollection, dto.getIsCollection());
        }
        //按照日期倒序排序
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage<WmMaterial> pageParam = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> resultPage = page(pageParam, wrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), resultPage.getTotal());
        List<WmMaterial> datas = resultPage.getRecords();
        //为每个图片加上前缀
        datas = datas.stream().map(item -> {
            item.setUrl(webSite + item.getUrl());
            return item;
        }).collect(Collectors.toList());
        result.setData(datas);
        return result;
    }

    /**
     * TODO 根据id删除素材图片
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delPictureById(Long id) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断当前图片是否问引用
        WmMaterial wmMaterial = getById(id);
        if (wmMaterial == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNewsMaterial::getMaterialId, id);
        Integer count = wmNewsMaterialMapper.selectCount(wrapper);
        if (count > 0) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "图片已被引用,无法删除");
        }
        // 删除素材库
        removeById(id);
        try {
            // 删除图片OSS
            fileStorageService.delete(wmMaterial.getUrl());
        } catch (Exception e) {
            e.printStackTrace();
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR, "OOS删除图片出现异常");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * TODO 根据id收藏素材图片
     *
     * @param id
     * @param type
     * @return
     */
    @Override
    public ResponseResult updateStatus(Long id, short type) {
        if (id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        //更新状态
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection, type)
                .eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, uid));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 检查文件格式 目前仅仅支持jpg  jpeg  png  gif 图片的上传
     *
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path) {
        if (StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if (path.endsWith(suffix)) {
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }

    /**
     * 检查文件大小,目前只支持2MB大小的文件
     *
     * @param multipartFile
     * @return false 超过默认值-拦截, true 允许
     */
    private boolean checkFileSize(MultipartFile multipartFile) {
        long multipartFileSize = multipartFile.getSize();
        long MaxSize = 2 * 1024 * 1024;
        if (multipartFileSize > MaxSize) {
            return false;
        }
        return true;

    }
}
